package com.sjh.tomcat.http;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

public class SjhRequest {

    private String method;
    private String uri;
    private HashMap<String, String> parametersMapping = new HashMap<>();
    private InputStream inputStream = null;

    // 构造器接收Socket的inpouStream，通过inputString获得HTTP请求，并封装
    public SjhRequest(InputStream inputStream){
        this.inputStream = inputStream;
        this.encapHttpRequest();
    }

    /**
     * 将http请求的相关数据进行封装
     */
    public void encapHttpRequest(){
        try {
            BufferedReader bufferedReader
                    = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            // 获取请求头
            String readLine = bufferedReader.readLine();
            // Get /uri?parameters Http/1.1 -> {Get, /uri?parameters, Http/1.1}
            String[] requestLineArr = readLine.split(" ");
            method = requestLineArr[0];
            int index = requestLineArr[1].indexOf("?");
            if(index == -1){
                uri = requestLineArr[1];
            }else{
                uri = requestLineArr[1].substring(0, index);
                String parameters = requestLineArr[1].substring(index + 1); // xx=1&bb=3&cc=5....
                if(null != parameters && !"".equals(parameters)){
                    String[] parametersPair = parameters.split("&"); // xx=1, bb=3, cc=5
                    for(String parameterPair : parametersPair){
                        String[] parameterVal = parameterPair.split("=");
                        if(parameterVal.length == 2){
                            parametersMapping.put(parameterVal[0], parameterVal[1]);
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getParameter(String name){
        if(parametersMapping.containsKey(name)) return parametersMapping.get(name);
        else return "";
    }

    @Override
    public String toString() {
        return "SjhRequest{" +
                "method='" + method + '\'' +
                ", uri='" + uri + '\'' +
                ", parametersMapping=" + parametersMapping +
                '}';
    }
}
